package com.app.android.coliy.dialog;

import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;

import com.app.android.coliy.R;
import com.app.android.coliy.callback.ClientCallBack;
import com.app.android.coliy.constant.Constants;
import com.app.android.coliy.interface_.CommCallBack;
import com.app.android.coliy.task.ClientThread;
import com.app.android.coliy.tool.Log;
import com.app.android.coliy.util.AnimUtil;
import com.app.android.coliy.util.StatusBarUtil_Dialog;
import com.app.android.coliy.util.Util;
import com.lzy.okgo.utils.HttpUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * Created by Administrator on 2018/8/29.
 */

public class Print_Dialog extends Dialog implements View.OnClickListener {
    public Print_Dialog(@NonNull Context context) {
        super(context, R.style.myDialog);
    }

    public Print_Dialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
    }

    protected Print_Dialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    CommCallBack callBack;
    Bitmap bitmap;
    BluetoothDevice device;
    Handler handler=new Handler();

    public void setData(Bitmap bitmap, BluetoothDevice device) {
        this.bitmap = bitmap;
        this.device = device;
    }

    public void setData( BluetoothDevice device) {
        this.device = device;
    }

    //设置输入回调
    public void setIntputCallBack(CommCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_print);
        initView();
        StatusBarUtil_Dialog.setImmersiveStatusBar(this, false);
        connectionBlueTooth();
    }

    LinearLayout ll_content;
    View view_bg;
    TextView tv_print;
    ImageView iv_img;
    ProgressBar progressbar, progressbar1;

    private void initView() {
        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        view_bg = findViewById(R.id.view_bg);
        view_bg.setOnClickListener(this);
        ll_content.setOnClickListener(this);
        AnimUtil.fadeIn(view_bg);
        AnimUtil.fadeIn(ll_content);

        iv_img = findViewById(R.id.iv_img);
        tv_print = findViewById(R.id.tv_print);
        progressbar = findViewById(R.id.progressbar);
        progressbar1 = findViewById(R.id.progressbar1);

        tv_print.setOnClickListener(this);

//        bitmap = BitmapUtil.rotateBitmap(bitmap, 90);
////        byte[] data = ImageDispose.Bitmap2Bytes(bitmap);
////        bitmap = ImageDispose.getPicFromBytes(data, null);
//
////        bitmap = BitmapUtil.compressQuality(bitmap, 30);
//        iv_img.setImageBitmap(bitmap);

    }

    ClientThread sendDataThread;
    ClientCallBack clientCallBack = new ClientCallBack() {
        @Override
        public void onScanStarted() {

        }

        @Override
        public void onScanFinished() {

        }

        @Override
        public void onScanning(BluetoothDevice device) {

        }

        @Override
        public void onBondRequest() {

        }

        @Override
        public void onBondSuccess(BluetoothDevice device) {

        }

        @Override
        public void onBonding(BluetoothDevice device) {

        }

        @Override
        public void onBondFail(BluetoothDevice device) {

        }

        @Override
        public void onConnectSuccess() {
            HttpUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_print.setText(Util.getString(R.string.printdialog_conneted));
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            sendData();
                        }
                    },500);
                }
            });
        }

        @Override
        public void onConnectFail(String errorMsg) {
            Log.i("errorMsg:" + errorMsg);
            HttpUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_print.setText(Util.getString(R.string.printdialog_fail));
                }
            });
        }

        @Override
        public void onConnectClose() {
//            HttpUtils.runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    CommToast.showToast(getContext(), "断开连接");
//                }
//            });
        }

        @Override
        public void onSend(final int progress) {
            try {
                HttpUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (progress == -1) {
                            tv_print.setText(Util.getString(R.string.printdialog_send_fail));
                            progressbar1.setVisibility(View.GONE);
                        } else if (progress == 100) {
                            disConnectionBlueTooth();
                            tv_print.setText(Util.getString(R.string.printdialog_send_success));
                            progressbar1.setVisibility(View.GONE);
                            progressbar.setProgress(100);
                        } else {
                            tv_print.setText(Util.getString(R.string.printdialog_sending));
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    //连接
    BluetoothSocket bluetoothSocket;
    public void connectionBlueTooth() {
        try {
            bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(Constants.uuid));
            if (bluetoothSocket != null && !bluetoothSocket.isConnected()) {
                sendDataThread = new ClientThread(bluetoothSocket, device, clientCallBack);
                sendDataThread.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //断开连接
    public void disConnectionBlueTooth() {
        try {
            bluetoothSocket.close();
            sendDataThread.closeSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void dismiss() {
        disConnectionBlueTooth();
        super.dismiss();
    }

    /**
     * 写数据
     */
    public void sendData() {
        if (sendDataThread != null) {
            String text = "1234";
            try {
                byte[] data = text.getBytes("UTF-8");
                sendDataThread.write(data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

//            byte[] data = buildPacket(ImageDispose.Bitmap2Bytes(bitmap), bitmap.getHeight());
//            Log.i("bitmap.getWidth:" + bitmap.getWidth() + "  " + bitmap.getHeight());
        }
    }

    public byte[] buildPacket(byte[] imageData, int imgHeight) {
        byte[] bytes = new byte[12 + imageData.length];   // 发送数据总长度为header 12字节 + png数据长度

        //头部数据
        byte[] head1 = intToByte(imageData.length);
        byte[] head2 = intToByte(0x88);
        byte[] head3 = intToByte(imgHeight);

        //组包  头部
        System.arraycopy(head1, 0, bytes, 0, 4);
        System.arraycopy(head2, 0, bytes, 4, 4);
        System.arraycopy(head3, 0, bytes, 8, 4);

        //组包  图像
        System.arraycopy(imageData, 0, bytes, 12, imageData.length);
        return bytes;    // 返回的就是组好包的 byte [], 通过FscBleCentralApi的send接口发送出去
    }

    public byte[] intToByte(int i) {
        byte[] result = new byte[4];
        // 由高位到低位
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_bg:
                dismissWithAnim();
                break;
            case R.id.ll_content:
                //不处理，只消耗点击事件
                break;
            case R.id.tv_print:
                sendData();
                break;
        }
    }

    public void dismissWithAnim() {
        if (view_bg.getAnimation() != null) return;
        AnimUtil.fadeOut(ll_content, null);
        AnimUtil.fadeOut(view_bg, new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                dismiss();
            }
        });
    }

    @Override
    public void onBackPressed() {
        dismissWithAnim();
    }

}
